// pages/reportList/reportDetail.js
var app = getApp();
var url = app.url;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: "",
    info: "",
    id: '',
    imgurl: "",
    lngLat: "",
    blockShow: false,
    remark: "",
    isWork: "",
    teamShow: false,
    teamList: [],
    personList: [],
    treamId: '',
    personId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    this.setData({
      id: options.id,
    });
    this.setData({ imgurl: app.imageUrl })
    this.getWorkState()
    this.getTeamList()
    console.log(id)

  },
  getTeamList() {
    var that = this;
    var params = {
      pageNumber: 1,
      pageSize: 10000,
      deptid: wx.getStorageSync('deptId'),
      type: 1,
    }
    var paramsCode = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/sysTream/getList.htm',
      data: paramsCode,
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr)
        console.log(rest)
        if (rest.isSuccess == 0) {
          var list = rest.result.content
          that.setData({
            teamList: list,
          })
        }
      },
      complete: function () {

      }
    })
  },
  getDetail() {
    var that = this;
    var params = { reportId: this.data.id };
    wx.request({
      url: url + '/web/exceptionReport/getExceptionReportById.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          var info = rest.reportInfo;
          info.imgList = info.imgUrl ? info.imgUrl.split(",") : []
          info.imgList.forEach((item, index, arr) => {
            arr[index] = that.data.imgurl + item

          })
          console.log(info.imgList)
          info.createTime = new Date(info.createTime).Format("yyyy-MM-dd hh:mm:ss");
          info.additionalNote = info.additionalNote ? JSON.parse(info.additionalNote) : []
          info.additionalNote.forEach(item => {
            item.imgUrl = item.imgUrl ? item.imgUrl.split(",").map(it => that.data.imgurl + it) : []
          })
          info.forwardNote = info.forwardNote ? JSON.parse(info.forwardNote) : []
          that.setData({ info: info })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getWorkState() {
    wx.request({
      url: 'https://www.huadulds.com/api/baseAccount/getSignTodayState?userId=' + wx.getStorageSync('userId'),
      data: {},
      method: "post",
      success: (res) => {
        var res = res.data;
        console.log(res);
        if (res.msg == "已签到") {
          this.setData({ isWork: true })
        }

      }
    })
  },
  toStart() {
    wx.request({
      url: 'https://www.huadulds.com/api/exceptionReport/dealWith?id=' + this.data.id,
      data: {},
      method: "post",
      success: (res) => {
        var res = res.data;
        console.log(res);
        if (res.code == 0) {
          wx.showToast({
            title: '已受理',
            duration: 1000,
          })
          this.getDetail()
        }
      }
    })
  },
  //查看地图
  openMap: function (e) {
    var that = this;
    const lngLat = e.currentTarget.dataset.index;

    const lng = +lngLat.split(',')[0];
    const lat = +lngLat.split(',')[1];
    if (lngLat != "") {

      // wx.openLocation({
      //   latitude: that.data.latitude,
      //   longitude: that.data.longitude,
      //   scale: 28
      // })
      // wx.navigateTo({
      //   url: '../littleMap/littleMap?latitude=' + that.data.latitude + '&longitude=' + that.data.longitude + '&id=' + this.data.info.distributionBoxid,
      // })
      if (this.data.info.reportType != 2 && this.data.info.reportType != 3) {
        wx.navigateTo({
          url: '../littleMap/littleMap?latitude=' + lat + '&longitude=' + lng + '&id=' + this.data.info.distributionBoxid,
        })
      } else {
        wx.openLocation({
          latitude: lat,
          longitude: lng,
          scale: 28
        })
      }

    }
  },
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
      success: function () {

      },
      fail: function () {

      }
    });
  },
  toHandle() {
    // this.setData({blockShow:true})
    wx.navigateTo({
      url: '../handle/handle?id=' + this.data.id,
    })
  },
  toBc() {
    // this.setData({blockShow:true})
    wx.navigateTo({
      url: '../supplement/supplement?id=' + this.data.id,
    })
  },
  toDelete() {
    this.exsubmit()
  },
  exsubmit: function (type) {
    var that = this;
    var id = this.data.id;
    var params = {
      reportId: id,
      userName: wx.getStorageSync('userName'),
      remark: this.data.remark,
      userId: wx.getStorageSync('userId'),
    };
    if (type) { params.type = 1 }
    console.log(params);
    wx.request({
      url: url + '/web/exceptionReport/wxdelById.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          that.setData({
            blockShow: false
          })
          wx.navigateBack()
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },
  //图预览
  img_tap: function (e) {
    var url = e.currentTarget.dataset.url;
    var imgList = e.currentTarget.dataset.imglist
    var pre_url = url
    wx.previewImage({
      current: pre_url, // 当前显示图片的http链接
      urls: imgList || this.data.info.imgList // 需要预览的图片http链接列表
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      remark: e.detail.value
    })
  },
  popupCancel() {
    this.setData({
      blockShow: false
    })
  },
  popupConfirm() {
    if (!this.data.remark) {
      wx.showModal({
        title: '提示',
        content: "请填写维修备注",
        showCancel: false
      })
      return
    }

    this.exsubmit(1)
  },
  openDialog(e) {
    var data = e.currentTarget.dataset;
    if (data.content) {
      this.setData({
        remarkTitle: data.title,
        remarkContent: data.content,
        remarkShow: true
      })
    }
  },
  closeRemark() {
    this.setData({
      remarkShow: false
    })
  },
  // 置顶
  toZd() {
    var that = this;
    var id = this.data.id;
    var params = {
      id,
      isTop: this.data.info.isTop == 1 ? 0 : 1,
    };
    console.log(params);
    wx.request({
      url: url + '/web/exceptionReport/reSetIsTop.htm',
      data: app.ecbEncrypto(params),
      method: 'POST',
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          wx.navigateBack()
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
      },

    })
  },
  showTeam() {
    this.setData({ teamShow: true })
  },
  checkboxChange: function (e) {
    var cboxs = e.detail.value;
    var val = cboxs.toString();
    let teamList = this.data.teamList
    teamList.forEach((item, index) => {
      item.checked = cboxs == item.id.toString()
    })
    this.setData({ treamId: val, teamList, personName: '' })
    if (cboxs) {
      this.getPersonList()
    } else {
      this.setData({ personList: [] })
    }
  },
  getPersonList() {
    var that = this;
    var list = this.data.list;
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = {
      pageSize: 1000,
      pageNumber: 1,
      treamId: that.data.treamId,
    }
    console.log(params);
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: url + '/web/baseAccount/getList2.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        console.log(decodingStr)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          that.setData({ personList: rest.result.content, })
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  personChange(e) {
    const cboxs = e.detail.value
    let personList = this.data.personList
    personList.forEach((item, index) => {
      item.checked = cboxs == item.id
    })
    this.setData({ personId: cboxs, personList })
  },
  submitZf() {
    var that = this;
    var list = this.data.list;
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = {
      id: this.data.id,
      localUserId: wx.getStorageSync('userId'),
    }
    if (this.data.personId) {
      params.userId = this.data.personId
    } else {
      params.treamId = this.data.treamId
    }
    if (!params.userId && !params.treamId) {
      wx.showModal({
        title: '提示',
        content: "请选择需要转发的班组或人员",
        showCancel: false
      })
      return
    }
    console.log(params);
    var encodingStr = app.ecbEncrypto(params);
    console.log(encodingStr);
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: url + '/web/exceptionReport/toForwarding.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        console.log(decodingStr)
        var rest = JSON.parse(decodingStr);
        console.log(rest)
        if (rest.isSuccess == 0) {
          wx.navigateBack()
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false
          })
        }
        console.log(rest)
      },
      complete: function () {
        wx.stopPullDownRefresh()
        that.setData({ showLoading: false })
        wx.hideLoading();
      }
    })
  },
  clearTeam() {
    this.setData({ teamShow: false })
  },
  getMoreBtn() {
    const topStr = this.data.info.isTop == 1 ? '取消置顶' : '置顶';
    let arr = [topStr, ];
    if(this.data.isWork && (this.data.info.dealwithstate == 1 || !this.data.info.dealwithstate)){
      arr.push('受理')
    }
    wx.showActionSheet({
      itemList: arr,
      success: (res) => {
        const { tapIndex } = res;
        console.log(res.tapIndex)
        if (tapIndex == 0) {
          this.toZd()
        } else if (tapIndex == 1) {
          this.toStart()
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  }
})

Date.prototype.Format = function (fmt) { //author: meizz  
  var o = {
    "M+": this.getMonth() + 1, //月份  
    "d+": this.getDate(), //日  
    "h+": this.getHours(), //小时  
    "m+": this.getMinutes(), //分  
    "s+": this.getSeconds(), //秒  
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度  
    "S": this.getMilliseconds() //毫秒  
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};